/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mam.rbac.application.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import com.foreveross.bsl.system.application.ApplicationRegisterApplication;
import com.foreveross.bsl.system.application.vo.ApplicationRegisterVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.foreveross.bsl.common.utils.bean.BeanHelper;
import com.foreveross.bsl.common.utils.context.ContextThead;
import com.foreveross.bsl.common.utils.enums.AccountStatus;
import com.foreveross.bsl.common.utils.enums.OperatEnum;
import com.foreveross.bsl.mam.model.rbac.domain.RbacUserRole;
import com.foreveross.bsl.mam.model.rbac.domain.Role;
import com.foreveross.bsl.mam.model.rbac.domain.User;
import com.foreveross.bsl.mam.rbac.application.RbacUserRoleApplication;
import com.foreveross.bsl.mam.rbac.application.UserCategoryApplication;
import com.foreveross.bsl.mam.rbac.application.vo.RbacUserRoleVO;
import com.foreveross.bsl.mam.rbac.application.vo.RoleVO;
import com.foreveross.bsl.mam.rbac.application.vo.UserVO;
import com.foreveross.bsl.mam.rbac.application.UserApplication;
import com.foreveross.bsl.mongodb.domain.Entity;


/**
 * <BR>
 * [功能详细描述]
 * @author Amberlo
 * @version [mam-application-impl , 2013-6-24] 
 */
@Named("rbacApplication")
public class RbacUserRoleApplicationImpl implements RbacUserRoleApplication {
	
	@Inject
	private UserCategoryApplication userCategoryApplication;
    @Inject
    private UserApplication userApplication;
    @Inject
    private ApplicationRegisterApplication applicationRegisterApplication;
	
	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.DatabaseInfoApplication#saveEntity(com.foreveross.bsl.system.application.vo.DatabaseInfoVO)
	 */
	@Override
	public RbacUserRoleVO saveEntity(RbacUserRoleVO entity) {
		RbacUserRole rbacUserRole = new RbacUserRole();
		BeanHelper.copyProperties(rbacUserRole, entity);
		rbacUserRole.save();
		entity.setId(rbacUserRole.getId());
		return entity;
	}
 
	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.DatabaseInfoApplication#deleteEntity(com.foreveross.bsl.system.application.vo.DatabaseInfoVO)
	 */
	@Override
	public void deleteEntity(RbacUserRoleVO entity) {
		User user = new User();
		BeanHelper.copyProperties(user, entity);
		user.delete();
	}

	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.DatabaseInfoApplication#getEntity(java.lang.String)
	 */
	@Override
	public RbacUserRoleVO getEntity(String id) {
		RbacUserRole user = new RbacUserRole();
		user = (RbacUserRole)user.findOne(id);
		RbacUserRoleVO vo = new RbacUserRoleVO();
		BeanHelper.copyProperties(vo, user);
		return vo;
	}

	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.DatabaseInfoApplication#findAll()
	 */
	@Override
	public List<RbacUserRoleVO> findAll() {
		RbacUserRole user = new RbacUserRole();
		Iterable iterable = user.findAll();
		if(iterable != null){
			List<RbacUserRoleVO> result = new ArrayList<RbacUserRoleVO>();
			RbacUserRoleVO vo;
			for (Iterator iterator = iterable.iterator(); iterator.hasNext();) {
				RbacUserRole obj = (RbacUserRole) iterator.next();

				vo = new RbacUserRoleVO();
				BeanHelper.copyProperties(vo, obj);
				result.add(vo);
			}
			return result;
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see com.foreveross.bsl.system.application.DatabaseInfoApplication#findByPageable(org.springframework.data.domain.Pageable)
	 */
	@Override
	public Page<RbacUserRoleVO> findByPage(int pageNumber, int pageSize) {
		User databaseInfo = new User();
		Pageable pageable=new PageRequest(pageNumber-1, pageSize);
		Page<Entity> page = databaseInfo.findAll(pageable);
		if(page != null && page.getContent() != null){
			List<RbacUserRoleVO> result = new ArrayList<RbacUserRoleVO>();
			RbacUserRoleVO vo;
			for (Entity po : page.getContent()) {
				User obj = (User) po;
				vo = new RbacUserRoleVO();
				BeanHelper.copyProperties(vo, obj);
				result.add(vo);
			}
			Page<RbacUserRoleVO> pageVO = new PageImpl<RbacUserRoleVO>(result, pageable, page.getTotalElements());
			return pageVO;
		}
		return null;
	}

	@Override
	public RbacUserRoleVO updateEntity(RbacUserRoleVO entity) {
		User databaseInfo = new User();
		BeanHelper.copyProperties(databaseInfo, entity);
		databaseInfo.save();
		BeanHelper.copyProperties(entity, databaseInfo);
		return null;
	}

	@Override
	public void addRolesIDToUser(String userID, List<String> rolesID) {
		
		//存表操作
		for(String rid:rolesID){
			RbacUserRole r = new RbacUserRole();
			r.setUser_ID(userID);
			r.setRole_ID(rid);
			r.save();
		}
	}

	@Override
	public void addUsersIdToRole(String roleID, List<String> usersID) {
		for(String uid:usersID){
			System.out.println("userID "+uid+" __ "+"roleID"+roleID);
			RbacUserRole r = new RbacUserRole();
			r.setUser_ID(uid);
			r.setRole_ID(roleID);
			System.out.println(r.toString());
			r.save();
		}
		
	}
	
	@Override
	public List<UserVO> getUsersByRoleID(String roleID) {
		List<UserVO> result = new ArrayList<UserVO>();
		RbacUserRole relation = new RbacUserRole();
		List<RbacUserRole> rlts = relation.findListByProperty("role_ID", OperatEnum.EQ, roleID);
		if(rlts!=null){
			for(RbacUserRole r : rlts){
				User user = new User();
				user = (User)user.findOne(r.getUser_ID());
				UserVO userVO = new UserVO();
				
				BeanHelper.copyProperties(userVO, user);
				
				if(user.getStatus().equals(AccountStatus.Disabled.getValue())){
					userVO.setLockOperation("活动");
					userVO.setLockStatus("锁定");
				}else {
					userVO.setLockOperation("锁定");
					userVO.setLockStatus("活动");
				}
				result.add(userVO);
			}
		}
		return result;
	}

	@Override
	public List<RoleVO> getRolesByUserID(String userID) {
		List<RoleVO> result = new ArrayList<RoleVO>();
		RbacUserRole relation = new RbacUserRole();
		List<RbacUserRole> rlts = relation.findListByProperty("user_ID", OperatEnum.EQ, userID);
		if(rlts!=null){
			for(RbacUserRole r : rlts){
				Role role = new Role();
				role = (Role)role.findOne(r.getRole_ID());
				RoleVO roleVO = new RoleVO();
				BeanHelper.copyProperties(roleVO, role);
				result.add(roleVO);
			}
		}
		return result;
	}
	

	@Override
	public void deleteByUserId(String userId) {
		RbacUserRole r = new RbacUserRole();
		List<RbacUserRole> rs = r.findListByProperty("user_ID", OperatEnum.EQ, userId);
		if(rs!=null&&rs.size()!=0){
			for (RbacUserRole rbacUserRole : rs) {
				rbacUserRole.delete();
			}
		}
	}
	
	@Override
	public void deleteByRoleId(String roleId) {
		RbacUserRole r = new RbacUserRole();
		List<RbacUserRole> rs = r.findListByProperty("role_ID", OperatEnum.EQ, roleId);
		if(rs!=null&&rs.size()!=0){
			for (RbacUserRole rbacUserRole : rs) {
				rbacUserRole.delete();
			}
		}
	}
	
	@Override
	public void deleteRolesIDToUser(String userID, String[] rolesID) {
		// TODO Auto-generated method stub
	}

	@Override
	public void deleteUsersIDToRole(String roleID, String[] usersID) {
		RbacUserRole r = new RbacUserRole();
		for(String userID:usersID){
			List<RbacUserRole> rs = r.findListByProperty(
						new String[]{"role_ID","user_ID"},
						new OperatEnum[]{OperatEnum.EQ,OperatEnum.EQ},
						new String[]{roleID,userID});
			if(rs!=null){
				for(RbacUserRole rbacUR:rs){
					r.delete(rbacUR.getId());
				}
			}
		}
		
	}

	@Override
	public List<UserVO> getMoreRoleUser(String roleID) {
		List<UserVO> result = new ArrayList<UserVO>();
		RbacUserRole relation = new RbacUserRole();
		List<RbacUserRole> rlts = relation.findListByProperty("role_ID", OperatEnum.EQ, roleID);
		if(rlts!=null){
			List<String> userIDs = new ArrayList<String>();
			for(RbacUserRole r : rlts){
				userIDs.add(r.getUser_ID());
			}
			User user = new User();
//			Query query = new Query();
//			query.addCriteria(new Criteria().where().nin(userIDs).);
//			System.out.println(query.toString());
			List<User> users = user.findListByQuery(Query.query(Criteria.where("id").nin(userIDs)));
			
			for(User u : users){
				UserVO userVO = new UserVO();
				BeanHelper.copyProperties(userVO, u);
				result.add(userVO);
			}
		}
		return result;
	}


    @Override
    public List<RoleVO> getRolesByUserName(String appKey, String username) {
        //切换数据库路由
        ApplicationRegisterVO arvo = applicationRegisterApplication.getByAppKey(appKey);
        ContextThead.setThreadVar(arvo.getUsername());

        List<RoleVO> roles = null;
        UserVO user = userApplication.getUserByUserName(username);
        if(user != null){
            String userId = user.getId();
            roles = getRolesByUserID(userId);
        }
        return roles;
    }
}
